import os

from django.conf import settings
from django.views import View

from Venue import Constants
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequired


class ImageView(View):
    """ 馆场图片 """

    def get(self, request):
        """ 查询 """
        dirs = os.listdir(Constants.Venue_Image_Path)
        lists = []
        for dir in dirs:
            url = f"{settings.LOCAL_URL}/static/venueImage/{dir}"
            lists.append(url)
        return Res.Json(Res.OK, result=lists)

    @LoginRequired.Venue
    def post(self, request):
        """ 修改 """
        index = request.POST.get("index")
        image = request.FILES.get("image")

        path = os.path.join(Constants.Venue_Image_Path, str(index))
        with open(path, "wb") as f:
            f.write(image.file.read())

        return Res.Json(Res.OK)

    @LoginRequired.Venue
    @Req.getJson
    def delete(self, request):
        """ 修改 """
        index = request.json_dict.get("index")

        path = os.path.join(Constants.Venue_Image_Path, str(index))
        if os.path.exists(path):
            os.remove(path)

        return Res.Json(Res.OK)
